package org.shindou09.easytagforpage.view.impl;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.shindou09.easytagforpage.Page;
import org.shindou09.easytagforpage.util.ClassLoaderUtil;
import org.shindou09.easytagforpage.view.PageView;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerPageViewImpl implements PageView{

	public final static String DEFAULT="org\\shindou09\\easytagforpage\\view\\ftl\\default.ftl";
	
	public final static String NUMBER="org\\shindou09\\easytagforpage\\view\\ftl\\number.ftl";
	
	private Configuration configuration;
	
	private String theme;
	
	public void setTheme(String theme) {
		if(theme==null || theme.toLowerCase().trim().equals("default")){
			this.theme=DEFAULT;
		}else if(theme.toLowerCase().trim().equals("number")){
			this.theme=NUMBER;
		}else{
			this.theme=theme.replace(".", "\\")+".ftl";
		}
	}
	
	public void getView(Page page,String pageUrl,Writer writer) {
		// TODO Auto-generated method stub
		if(configuration==null){
			configuration=new Configuration();
		}
		try {
			ClassTemplateLoader ctl=new ClassTemplateLoader(getClass(),"");
			EasyTagForPageClassTemplateLoader ect=new EasyTagForPageClassTemplateLoader();
			configuration.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[]{
					ctl,ect
			}));
			Template template = configuration.getTemplate(this.theme);
			template.setEncoding("utf-8");
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("page", page);
			map.put("pageUrl", pageUrl);
			template.process(map, writer);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static class EasyTagForPageClassTemplateLoader extends URLTemplateLoader{

		@Override
		protected URL getURL(String name) {
			// TODO Auto-generated method stub
			if(name.indexOf("\\")>0){
				name=name.replace("\\", "/");
			}
			return FreeMarkerPageViewImpl.class.getClassLoader().getResource(name);
		}
		
	}

}
